import os
import shutil
import sys
from pathlib import Path

from PyQt6.QtGui import QIntValidator, QPixmap, QPainter, QIcon
from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QListWidget, QPushButton, QLabel, QSlider,
    QComboBox, QLineEdit, QListWidgetItem, QCheckBox, QFileDialog, QProgressDialog, QMessageBox, QStatusBar
)
from PyQt6.QtCore import Qt, QTimer, QUrl
from sqlalchemy.orm import joinedload

from core.database import SessionLocal
from core.models import Video
from core.operations import get_all_videos, rate_video, search_videos, add_tag_to_video, get_video_by_id, get_all_tags, \
    search_videos_advanced, update_tag, delete_tag, add_tag
from qfluentwidgets import FluentWindow, NavigationItemPosition, setTheme, Theme, PrimaryPushButton, ComboBox, LineEdit, \
    ListWidget, Slider, CheckBox, CaptionLabel, StrongBodyLabel, BodyLabel, FluentIcon as FIF, PushButton
from qfluentwidgets.multimedia import VideoWidget

class VideoPlayerWindow(FluentWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("我的电影")
        self.resize(1400, 900)
        setTheme(Theme.LIGHT)  # 使用浅色主题
        # 设置窗口图标
        icon_path = str(Path(__file__).parent / "resources" / "favicon.ico")
        if Path(icon_path).exists():
            self.setWindowIcon(QIcon(icon_path))
        else:
            print(f"警告: 图标文件未找到 - {icon_path}")
        self.setup_ui()
        self.load_real_data()
        self.setup_connections()  # 连接所有按钮和功能


    def setup_ui(self):
        # 创建内容页面
        self.create_video_management_interface()
        self.create_statistics_interface()
        self.create_settings_interface()

        self.addSubInterface(
            interface=self.video_interface,
            icon=FIF.VIDEO,
            text='视频管理',
            position=NavigationItemPosition.TOP,
            parent=None,
            isTransparent=False
        )

        self.addSubInterface(
            interface=self.statistics_interface,
            icon=FIF.BUS,
            text='统计分析',
            position=NavigationItemPosition.TOP,
            parent=None,
            isTransparent=False
        )

        self.addSubInterface(
            interface=self.settings_interface,
            icon=FIF.SETTING,
            text='设置',
            position=NavigationItemPosition.TOP,
            parent=None,
            isTransparent=False
        )






    def create_video_management_interface(self):
        """创建视频管理界面"""
        self.video_interface = QWidget()
        self.video_interface.setObjectName("videoInterface")
        layout = QVBoxLayout(self.video_interface)

        # 左侧视频列表区域
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)

        # 搜索表格单按钮
        self.import_btn = PrimaryPushButton("导入视频")  # 添加导入按钮
        import_layout = QHBoxLayout()
        import_layout.addWidget(self.import_btn)

        # 搜索框
        search_layout = QHBoxLayout()
        self.search_input = LineEdit()
        self.search_input.setPlaceholderText("输入视频名称...")
        self.search_btn = PrimaryPushButton("搜索")
        search_layout.addWidget(self.search_input)
        search_layout.addWidget(self.search_btn)

        # 筛选选项
        filter_layout = QHBoxLayout()
        self.search_tag_combo = ComboBox()
        self.search_tag_combo.addItem(None)
        filter_layout.addWidget(self.search_tag_combo)

        self.search_score_input = LineEdit()
        self.search_score_input.setPlaceholderText("1-10")
        self.search_score_input.setFixedWidth(70)
        filter_layout.addWidget(self.search_score_input)

        self.untagged_check = CheckBox("仅未标记")
        self.unrated_check = CheckBox("仅未评分")
        filter_layout.addWidget(self.untagged_check)
        filter_layout.addWidget(self.unrated_check)

        # 视频列表
        self.video_list = ListWidget()
        self.video_list.setStyleSheet("font-size: 14px;")
        self.video_list.itemDoubleClicked.connect(self.on_video_double_clicked)

        left_layout.addLayout(import_layout)  # 添加导入按钮布局
        left_layout.addLayout(search_layout)
        left_layout.addLayout(filter_layout)
        left_layout.addWidget(self.video_list, 1)

        # 右侧视频播放和操作区域
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)

        # 视频播放区域
        self.video_widget = VideoWidget(self)  #
        self.video_widget.setMinimumSize(800, 500)

        # 标签和评分编辑区
        edit_layout = QHBoxLayout()
        edit_layout.setSpacing(5)  # 减小组件之间的间距

        self.tag_combo = ComboBox()
        self.tag_combo.setFixedWidth(120)  # 设置组合框的宽度
        edit_layout.addWidget(self.tag_combo)

        self.score_input = LineEdit()
        self.score_input.setFixedWidth(70)
        self.score_input.setPlaceholderText("1-10")
        edit_layout.addWidget(self.score_input)

        self.save_btn = PrimaryPushButton("保存")
        edit_layout.addWidget(self.save_btn)

        # 操作按钮
        btn_layout = QHBoxLayout()
        self.delete_btn = PrimaryPushButton("删除")
        btn_layout.addWidget(self.delete_btn)

        self.batch_delete_btn = PrimaryPushButton("批量删除")
        btn_layout.addWidget(self.batch_delete_btn)

        self.batch_archive_btn = PrimaryPushButton("批量归档")
        btn_layout.addWidget(self.batch_archive_btn)

        right_layout.addWidget(self.video_widget)
        right_layout.addLayout(edit_layout)
        right_layout.addLayout(btn_layout)

        # 整合左右布局
        main_layout = QHBoxLayout()
        main_layout.addWidget(left_panel, 1)
        main_layout.addWidget(right_panel, 3)
        layout.addLayout(main_layout)

    def create_statistics_interface(self):
        """创建统计数据界面"""
        self.statistics_interface = QWidget()
        self.statistics_interface.setObjectName("statisticsInterface")
        layout = QVBoxLayout(self.statistics_interface)

        # 添加统计信息卡片
        layout.addWidget(StrongBodyLabel("视频统计"))
        layout.addWidget(BodyLabel(f"总视频数量: {self.get_total_videos()}"))
        layout.addWidget(BodyLabel(f"已评分视频: {self.get_rated_videos()}"))
        layout.addWidget(BodyLabel(f"未评分视频: {self.get_unrated_videos()}"))

    def create_settings_interface(self):
        """创建标签管理界面（优化版）"""
        self.settings_interface = QWidget()
        self.settings_interface.setObjectName("settingsInterface")
        layout = QVBoxLayout(self.settings_interface)
        layout.setContentsMargins(10, 5, 10, 10)  # 减少上下左右边距
        layout.setSpacing(8)  # 减少组件间距

        # 标签管理标题（紧凑布局）
        title = StrongBodyLabel("标签管理")
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title, alignment=Qt.AlignmentFlag.AlignTop)

        # 标签列表（带边框）
        self.tag_list = ListWidget()
        self.tag_list.setStyleSheet("""
            QListWidget {
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                padding: 2px;
                background: white;
            }
            QListWidget::item {
                padding: 4px 8px;
                border-bottom: 1px solid #f0f0f0;
            }
            QListWidget::item:selected {
                background: #e1f5fe;
                color: black;
            }
        """)
        self.tag_list.setFixedHeight(800)  # 适当高度
        self.tag_list.setFixedWidth(200)
        layout.addWidget(self.tag_list)

        # 标签编辑区域（紧凑布局）
        edit_layout = QHBoxLayout()
        edit_layout.setSpacing(6)
        self.tag_input = LineEdit()
        self.tag_input.setPlaceholderText("输入标签名称")
        self.tag_input.setClearButtonEnabled(True)
        edit_layout.addWidget(self.tag_input, stretch=2)  # 输入框占据更多空间

        # 操作按钮（紧凑布局）
        self.add_tag_btn = PrimaryPushButton("添加")
        self.update_tag_btn = PrimaryPushButton("更新")
        self.delete_tag_btn = PrimaryPushButton("删除")

        # 设置按钮固定宽度
        for btn in [self.add_tag_btn, self.update_tag_btn, self.delete_tag_btn]:
            btn.setFixedWidth(70)
            edit_layout.addWidget(btn, stretch=2)

        layout.addLayout(edit_layout)

        # 连接信号
        self.add_tag_btn.clicked.connect(self.on_add_tag)
        self.update_tag_btn.clicked.connect(self.on_update_tag)
        self.delete_tag_btn.clicked.connect(self.on_delete_tag)

        # 加载标签数据
        self.load_tag_list()

    def load_tag_list(self):
        """加载标签列表"""
        try:
            tags = get_all_tags()
            self.tag_list.clear()
            for tag in tags:
                item = QListWidgetItem(tag.name)
                item.setData(Qt.ItemDataRole.UserRole, tag.id)
                self.tag_list.addItem(item)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载标签失败: {str(e)}")

    def on_add_tag(self):
        """添加新标签"""
        tag_name = self.tag_input.text().strip()
        if not tag_name:
            QMessageBox.warning(self, "提示", "请输入标签名称")
            return

        try:
            add_tag(tag_name)
            self.load_tag_list()
            self.tag_input.clear()
            self.load_tags()  # 刷新其他界面的标签下拉框
            QMessageBox.information(self, "成功", "标签添加成功")
        except ValueError as e:
            QMessageBox.warning(self, "错误", str(e))

    def on_update_tag(self):
        """更新选中标签"""
        selected = self.tag_list.currentItem()
        if not selected:
            QMessageBox.warning(self, "提示", "请先选择一个标签")
            return

        new_name = self.tag_input.text().strip()
        if not new_name:
            QMessageBox.warning(self, "提示", "请输入新的标签名称")
            return

        tag_id = selected.data(Qt.ItemDataRole.UserRole)
        try:
            update_tag(tag_id, new_name)
            self.load_tag_list()
            self.tag_input.clear()
            self.load_tags()  # 刷新其他界面的标签下拉框
            QMessageBox.information(self, "成功", "标签更新成功")
        except ValueError as e:
            QMessageBox.warning(self, "错误", str(e))

    def on_delete_tag(self):
        """删除选中标签"""
        selected = self.tag_list.currentItem()
        if not selected:
            QMessageBox.warning(self, "提示", "请先选择一个标签")
            return

        tag_name = selected.text()
        confirm = QMessageBox.question(
            self, "确认删除",
            f"确定要删除标签 '{tag_name}' 吗?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        if confirm != QMessageBox.StandardButton.Yes:
            return

        tag_id = selected.data(Qt.ItemDataRole.UserRole)
        try:
            delete_tag(tag_id)
            self.load_tag_list()
            self.load_tags()  # 刷新其他界面的标签下拉框
            QMessageBox.information(self, "成功", "标签删除成功")
        except ValueError as e:
            QMessageBox.warning(self, "错误", str(e))
        except Exception as e:
            QMessageBox.critical(self, "错误", f"删除标签失败: {str(e)}")

    def get_total_videos(self):
        """获取总视频数量"""
        db = SessionLocal()
        try:
            return db.query(Video).count()
        finally:
            db.close()

    def get_rated_videos(self):
        """获取已评分视频数量"""
        db = SessionLocal()
        try:
            return db.query(Video).filter(Video.score.isnot(None)).count()
        finally:
            db.close()

    def get_unrated_videos(self):
        """获取未评分视频数量"""
        db = SessionLocal()
        try:
            return db.query(Video).filter(Video.score.is_(None)).count()
        finally:
            db.close()

    def setup_connections(self):
        """设置控件之间的连接"""
        self.search_btn.clicked.connect(self.on_search)
        self.save_btn.clicked.connect(self.on_save)
        self.delete_btn.clicked.connect(self.on_delete)
        self.batch_delete_btn.clicked.connect(self.on_batch_delete)
        self.batch_archive_btn.clicked.connect(self.on_batch_archive)
        self.import_btn.clicked.connect(self.on_import_videos)
        self.load_tags()

    def on_batch_archive(self):
        confirm = QMessageBox.question(
            self, "确认归档",
            f"即将归档所有符合当前搜索条件的视频（共{len(self.video_list)}个）\n确定继续吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        if confirm != QMessageBox.StandardButton.Yes:
            return
        """根据当前搜索条件批量归档视频"""
        try:
            # 获取当前搜索条件
            keyword = self.search_input.text().strip() or None
            tag_name = self.search_tag_combo.currentText()
            score = float(self.search_score_input.text()) if self.search_score_input.text() else None
            untagged_only = self.untagged_check.isChecked()
            unrated_only = self.unrated_check.isChecked()

            db = SessionLocal()

            # 查询符合条件的视频（预加载标签）
            videos = search_videos_advanced(
                db=db,
                name=keyword,
                tag_name=tag_name,
                score=score,
                untagged_only=untagged_only,
                unrated_only=unrated_only
            )

            if not videos:
                return

            # 创建进度对话框
            progress = QProgressDialog("批量归档中...", "取消", 0, len(videos), self)
            progress.setWindowTitle("归档进度")
            progress.setWindowModality(Qt.WindowModality.WindowModal)

            success_count = 0
            fail_count = 0

            for i, video in enumerate(videos):
                if progress.wasCanceled():
                    break

                progress.setValue(i)
                progress.setLabelText(f"正在处理: {video.name[:20]}...")

                try:
                    if not video.url:
                        fail_count += 1
                        continue

                    src_path = Path(video.url)
                    if not src_path.exists():
                        fail_count += 1
                        continue

                    # 获取标签名称（至少一个标签）
                    tag_names = [tag.name for tag in video.tags]
                    if not tag_names:
                        if not untagged_only:  # 如果不是专门查未标记视频
                            fail_count += 1
                            continue
                        tag_names = ["未标记"]

                    # 构建归档路径（格式：父目录/主标签/评分/文件名）
                    parent_dir = src_path.parent.parent
                    main_tag = tag_names[0]  # 使用第一个标签作为主分类
                    score_str = str(video.score) if video.score is not None else "未评分"

                    dest_dir = parent_dir / main_tag / score_str
                    dest_dir.mkdir(parents=True, exist_ok=True)

                    # 移动文件
                    dest_path = dest_dir / src_path.name
                    shutil.move(str(src_path), str(dest_path))

                    # 更新数据库
                    video.url = str(dest_path)
                    success_count += 1

                except Exception as e:
                    print(f"归档失败 {video.name}: {str(e)}")
                    fail_count += 1

            db.commit()
            progress.close()

            # 刷新界面
            self.load_real_data()

            # 显示结果
            msg = f"归档完成: 成功 {success_count} 个, 失败 {fail_count} 个"

        except Exception as e:
            print(f"批量归档错误: {e}")
        finally:
            db.close()
    def on_import_videos(self):
        """导入视频文件到数据库"""
        try:
            # 选择文件夹对话框
            directory = QFileDialog.getExistingDirectory(
                self,
                "选择视频文件夹",
                os.path.expanduser("~")  # 默认从用户目录开始
            )

            if not directory:
                return  # 用户取消了选择

            # 支持的视频格式
            video_extensions = (
                '.mp4', '.ts', '.avi', '.mov', '.wmv',
                '.flv', '.mkv', '.webm', '.mpeg',
                '.mpg', '.3gp', '.ogg'
            )

            # 获取数据库会话
            db = SessionLocal()

            try:
                imported_count = 0
                skipped_count = 0

                # 遍历文件夹
                for root, _, files in os.walk(directory):
                    for file in files:
                        if file.lower().endswith(video_extensions):
                            video_path = Path(root) / file

                            # 检查是否已存在
                            existing = db.query(Video).filter(
                                Video.name == file
                            ).first()

                            if existing:
                                skipped_count += 1
                                continue

                            # 添加到数据库
                            db_video = Video(
                                name=file,
                                url=str(video_path)
                            )
                            db.add(db_video)
                            imported_count += 1

                db.commit()

                # 刷新列表
                self.load_real_data()

                # 显示结果
                msg = f"导入完成: 新增 {imported_count} 个, 跳过 {skipped_count} 个已存在视频"

            except Exception as e:
                db.rollback()
                print(f"导入错误: {e}")
            finally:
                db.close()

        except Exception as e:
            print(f"文件夹选择错误: {e}")





    def on_video_double_clicked(self, item):
        """处理视频列表双击事件"""
        self.play_selected()  # 直接调用现有的播放方法

    def load_tags(self):
        """加载标签到两个下拉框"""
        try:
            tags = get_all_tags()
            self.tag_combo.clear()
            self.search_tag_combo.clear()

            # 添加标签到编辑下拉框
            self.tag_combo.addItem(None)
            for tag in sorted(tags, key=lambda x: x.name):
                self.tag_combo.addItem(tag.name)

            # 添加标签到搜索下拉框
            self.search_tag_combo.addItem(None)
            for tag in sorted(tags, key=lambda x: x.name):
                self.search_tag_combo.addItem(tag.name)
        except Exception as e:
            print(f"Error loading tags: {e}")  # 打印异常信息
            QMessageBox.critical(self, "错误", f"加载标签时出错: {str(e)}")

    def load_real_data(self):
        """从数据库加载真实数据（修复会话问题）"""
        db = SessionLocal()
        try:
            # 使用 joinedload 预加载 tags
            videos = db.query(Video).options(joinedload(Video.tags)).all()

            self.video_list.clear()
            for video in videos:
                item = QListWidgetItem()
                text = f"{video.name}\n"
                text += f"标签: {', '.join(tag.name for tag in video.tags)}\n" if video.tags else "标签: 无\n"
                text += f"评分: {video.score if video.score is not None else '未评分'}"

                item.setText(text)
                item.setData(Qt.ItemDataRole.UserRole, video.id)
                self.video_list.addItem(item)
        finally:
            db.close()

    # ========== 数据库交互方法 ==========

    def on_save(self):
        """保存标签和评分"""
        selected_item = self.video_list.currentItem()
        if not selected_item:
            return

        video_id = selected_item.data(Qt.ItemDataRole.UserRole)

        # 保存评分
        score_text = self.score_input.text()
        if score_text:
            try:
                score = int(score_text)
                if 1 <= score <= 10:
                    rate_video(video_id, float(score))
                else:
                    return
            except ValueError:
                return

        # 保存标签
        tag_name = self.tag_combo.currentText()
        if tag_name is not None:  # 确保不是"选择标签"
            add_tag_to_video(video_id, tag_name)

        self.load_real_data()  # 刷新列表显示新评分
        self.on_search()

    def on_search(self):
        self.setCursor(Qt.CursorShape.WaitCursor)
        """执行高级搜索（修复会话问题）"""
        try:
            # 获取搜索条件
            keyword = self.search_input.text().strip() or None
            tag_name = self.search_tag_combo.currentText()
            score = float(self.search_score_input.text()) if self.search_score_input.text() else None
            untagged_only = self.untagged_check.isChecked()
            unrated_only = self.unrated_check.isChecked()

            # 获取数据库会话
            db = SessionLocal()

            try:
                # 调用高级搜索
                videos = search_videos_advanced(
                    db=db,
                    name=keyword,
                    tag_name=tag_name,
                    score=score,
                    untagged_only=untagged_only,
                    unrated_only=unrated_only
                )

                # 在会话关闭前处理所有需要的关系数据
                video_data = []
                for video in videos:
                    # 在会话有效时获取标签信息
                    tag_names = [tag.name for tag in video.tags] if video.tags else []
                    video_data.append({
                        'id': video.id,
                        'name': video.name,
                        'tags': tag_names,
                        'score': video.score,
                        'url': video.url
                    })

                # 显示结果
                self.video_list.clear()
                for data in video_data:
                    item = QListWidgetItem()
                    text = f"{data['name']}\n"
                    text += f"标签: {', '.join(data['tags'])}\n" if data['tags'] else "标签: 无\n"
                    text += f"评分: {data['score'] if data['score'] is not None else '未评分'}"
                    item.setText(text)
                    item.setData(Qt.ItemDataRole.UserRole, data['id'])
                    self.video_list.addItem(item)

            finally:
                # 确保会话关闭
                db.close()

        except Exception as e:
            print(f"搜索错误: {e}")

    def on_delete(self):
        """删除选中视频（数据库记录+本地文件）"""
        selected_items = self.video_list.selectedItems()
        if not selected_items:
            return

        # 确认对话框（显示更详细的信息）
        video_names = [item.text().split('\n')[0] for item in selected_items]
        confirm_msg = QMessageBox()
        confirm_msg.setIcon(QMessageBox.Icon.Warning)
        confirm_msg.setWindowTitle("确认删除")
        confirm_msg.setText(f"即将永久删除以下 {len(selected_items)} 个视频:")
        confirm_msg.setInformativeText("\n".join(f"• {name[:30]}..." if len(name) > 30 else f"• {name}"
                                                 for name in video_names[:5]))  # 最多显示5个
        if len(video_names) > 5:
            confirm_msg.setDetailedText("\n".join(video_names[5:]))
        confirm_msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)

        if confirm_msg.exec() != QMessageBox.StandardButton.Yes:
            return

        db = SessionLocal()
        success_count = 0
        fail_count = 0
        failed_files = []

        # 进度对话框（针对多选情况）
        progress = None
        if len(selected_items) > 3:
            progress = QProgressDialog("删除中...", "取消", 0, len(selected_items), self)
            progress.setWindowModality(Qt.WindowModality.WindowModal)

        try:
            for i, item in enumerate(selected_items):
                if progress and progress.wasCanceled():
                    break


                video_id = item.data(Qt.ItemDataRole.UserRole)
                video = db.query(Video).filter(Video.id == video_id).first()

                if not video:
                    continue

                try:
                    # 删除本地文件（带安全检查）
                    if video.url:
                        file_path = Path(video.url)
                        if file_path.exists():
                            try:
                                # 尝试先关闭可能打开的文件句柄
                                if sys.platform == "win32":
                                    os.system(f'handle.exe /p {file_path} > NUL 2>&1')
                                file_path.unlink()
                                print(f"已删除文件: {file_path}")
                            except PermissionError as pe:
                                raise Exception(f"文件被占用或无权限: {str(pe)}")
                            except Exception as e:
                                raise Exception(f"文件删除失败: {str(e)}")

                    # 删除数据库记录
                    db.delete(video)
                    db.commit()
                    success_count += 1

                except Exception as e:
                    db.rollback()
                    fail_count += 1
                    failed_files.append(f"{video.name}: {str(e)}")
                    print(f"删除错误 {video.name}: {e}")

            # 刷新列表
            self.load_real_data()

            # 显示结果
            msg = f"删除完成: 成功 {success_count} 个"
            if fail_count > 0:
                msg += f", 失败 {fail_count} 个\n失败原因: {', '.join(failed_files[:3])}"  # 最多显示3个失败原因
                if len(failed_files) > 3:
                    msg += " 等..."


        except Exception as e:
            db.rollback()
        finally:
            if progress:
                progress.close()
            db.close()

    def on_batch_delete(self):
        """根据当前搜索条件批量删除视频"""
        # 获取当前搜索条件
        keyword = self.search_input.text().strip() or None
        tag_name = self.search_tag_combo.currentText()
        score = float(self.search_score_input.text()) if self.search_score_input.text() else None
        untagged_only = self.untagged_check.isChecked()
        unrated_only = self.unrated_check.isChecked()

        db = SessionLocal()
        try:
            # 查询符合条件的视频
            videos = search_videos_advanced(
                db=db,
                name=keyword,
                tag_name=tag_name,
                score=score,
                untagged_only=untagged_only,
                unrated_only=unrated_only
            )

            if not videos:
                return

            # 增强型确认对话框
            confirm = QMessageBox(self)
            confirm.setIcon(QMessageBox.Icon.Warning)
            confirm.setWindowTitle("危险操作确认")
            confirm.setText(f"即将永久删除 {len(videos)} 个符合当前搜索条件的视频！")
            confirm.setInformativeText("此操作将同时删除数据库记录和本地文件，且不可恢复！")

            # 添加显示前5个视频名称
            sample_names = "\n".join([f"• {v.name[:30]}..." if len(v.name) > 30 else f"• {v.name}"
                                      for v in videos[:5]])
            confirm.setDetailedText(f"示例视频:\n{sample_names}")

            # 添加二次确认复选框
            confirm.setCheckBox(QCheckBox("我理解此操作的危险性，确认删除"))
            confirm.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)

            if confirm.exec() != QMessageBox.StandardButton.Yes or not confirm.checkBox().isChecked():
                return

            # 进度对话框
            progress = QProgressDialog("批量删除中...", "取消", 0, len(videos), self)
            progress.setWindowTitle("删除进度")
            progress.setWindowModality(Qt.WindowModality.WindowModal)

            success_count = 0
            fail_count = 0
            failed_items = []

            for i, video in enumerate(videos):
                if progress.wasCanceled():
                    break

                progress.setValue(i)
                progress.setLabelText(f"正在处理: {video.name[:20]}...")

                try:
                    # 删除本地文件
                    if video.url:
                        file_path = Path(video.url)
                        if file_path.exists():
                            try:
                                # Windows系统尝试解除文件占用
                                if sys.platform == "win32":
                                    try:
                                        import win32api
                                        win32api.SetFileAttributes(str(file_path), win32api.FILE_ATTRIBUTE_NORMAL)
                                    except:
                                        pass
                                file_path.unlink()
                            except Exception as e:
                                raise Exception(f"文件删除失败: {str(e)}")

                    # 删除数据库记录
                    db.delete(video)
                    db.commit()
                    success_count += 1

                except Exception as e:
                    db.rollback()
                    fail_count += 1
                    failed_items.append(f"{video.name}: {str(e)}")
                    print(f"删除失败 {video.name}: {e}")

            progress.close()

            # 刷新数据
            self.load_real_data()

            # 显示详细结果
            result_msg = QMessageBox(self)
            result_msg.setWindowTitle("删除结果")
            result_msg.setText(f"操作完成: 成功 {success_count} 个, 失败 {fail_count} 个")

            if failed_items:
                result_msg.setDetailedText("\n".join(failed_items[:10]))  # 最多显示10个失败项
            result_msg.exec()

        except Exception as e:
            print(f"批量删除错误: {e}")
        finally:
            db.close()


    # ========== 播放控制方法 ==========
    def play_selected(self):
        selected_item = self.video_list.currentItem()
        if not selected_item:
            return

        video_id = selected_item.data(Qt.ItemDataRole.UserRole)
        video = get_video_by_id(video_id)

        if video and video.url:
            video_path = Path(video.url)
            if video_path.exists():
                self.video_widget.setUpdatesEnabled(False)  # 禁用刷新
                self.video_widget.setVideo(QUrl.fromLocalFile(str(video_path)))
                self.video_widget.play()
                self.video_widget.setUpdatesEnabled(True)  # 恢复刷新
            else:
                # 视频文件不存在，从数据库中删除记录
                self.delete_video_from_db(video_id)
                QMessageBox.warning(self, "错误", f"视频文件不存在: {video_path}")
        else:
            QMessageBox.warning(self, "错误", "未找到视频或视频路径无效")
    def delete_video_from_db(self, video_id):
        """仅从数据库中删除视频记录"""
        db = SessionLocal()
        try:
            video = db.query(Video).filter(Video.id == video_id).first()
            if video:
                db.delete(video)
                db.commit()
                print(f"已从数据库中删除视频记录: {video.name}")
            else:
                print(f"未找到数据库中的视频记录: {video_id}")
        except Exception as e:
            db.rollback()
            print(f"从数据库中删除视频记录失败: {e}")
        finally:
            db.close()



